{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.LSTMCell(size_layer,initializer=tf.orthogonal_initializer(),reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongMonotonicAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state_c = tf.concat((state_fw.c, state_bw.c), -1)\n",
    "        bi_state_h = tf.concat((state_fw.h, state_bw.h), -1)\n",
    "        bi_lstm_state = tf.nn.rnn_cell.LSTMStateTuple(c=bi_state_c, h=bi_state_h)\n",
    "        encoder_state = tuple([bi_lstm_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-6d6e795642bc>:12: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-6d6e795642bc>:40: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:958: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:962: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-6d6e795642bc>:19: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[13764,  9943,  9943,  9943,  9943,    71,    71,    71, 31683,\n",
       "         31683, 31683, 31683, 20783, 20783,  2946, 30402, 30402, 30402,\n",
       "         30402,  4911,  4911,  4911,  4911,  4911, 23574, 23574, 23574,\n",
       "         26997, 26997, 26997, 26997, 21008, 21008, 21008,    57,    57,\n",
       "            57,  5543,  5543,  5543,  5543,  5543, 31886, 31886, 19864,\n",
       "         19864, 25798, 25798, 25798, 26882, 26882, 21539, 21539, 21539,\n",
       "         21539,  7265,  7265, 14401, 14401, 22604, 22604, 22604, 22604,\n",
       "         22604, 31174, 31174, 31174, 31174, 31332, 31332, 25614, 25614],\n",
       "        [26180, 26180, 26180,  8869,  8869, 23088, 23088, 23088, 24766,\n",
       "         24766, 24766, 24766, 24766, 24766,  8140,  8140,  1537,  1537,\n",
       "          6285,  6285,   412,  6285,  6285,  6285,  6285,  6285, 27420,\n",
       "          6285, 22508, 22508, 22508, 31892, 31892, 15068, 31892, 31892,\n",
       "         31892, 31892, 16849, 16849,  2215,  2215,  2215, 20435, 20435,\n",
       "         20435, 25981, 25981, 25981, 25981, 25981, 28458, 28458, 28458,\n",
       "         20028, 20028, 20028, 18530, 18530, 18530, 18530, 18530, 14979,\n",
       "          6706,  6706,  6576,  6576, 18530, 18530, 18530,  7059,  9706],\n",
       "        [29349, 29349, 29349, 17487, 17487, 11336, 11336, 11336, 13102,\n",
       "         13102, 13102, 13102, 11773, 23295, 14379, 14379, 14379,  3413,\n",
       "          3413, 23454,  8322, 12988, 12988, 24230, 24230, 24230, 26781,\n",
       "         26781, 26781, 26781, 30630, 30630, 30630, 30630, 24549, 24549,\n",
       "         24549, 24549, 24549,  6738,  6738,  6738,  6738,  6738,  6738,\n",
       "          6738,  6738,  6738, 15861, 29311, 29311, 29311, 29311, 29311,\n",
       "         11138, 23344, 23344, 23344, 23344, 18168, 18168, 26465, 26465,\n",
       "         26465, 26465, 26465, 26465, 14934, 13228, 13228,  1212,  1212],\n",
       "        [11295, 11295,  6155,  6155,  6155, 23357,  7313,  7313,  7313,\n",
       "          7313,  7313,  3558,  3558, 11456, 11456, 11456,  5703,  5703,\n",
       "          5703,  5703,  5703, 12740, 17465,  2786,  2786,  2786, 30724,\n",
       "         28170, 28170,  6997, 18855, 18855, 18855, 18855, 18855, 11598,\n",
       "         11598, 11598,  4196, 11598,  4196,  4196, 15285, 15285, 22764,\n",
       "         22764, 30013, 30013, 30013, 30013, 13052, 15276, 23860, 23860,\n",
       "         23860, 23860, 23860, 23860, 31283, 31283, 31283, 31283,  5790,\n",
       "          5790,  5790, 15935, 15935, 17368,   693,   693, 17368, 17368],\n",
       "        [ 3359,  9710, 13616, 13616, 13616,  8382,  8382,  8382,  4783,\n",
       "          4783,  4783,   853,   853,   853, 26289, 26289, 26289, 21892,\n",
       "         17942, 17942, 17942, 17942,  3689,  3689,  3689,  3748,  3748,\n",
       "         22205,  9216,  9216,  9216,  5663,  5663,  5663,  5663,  5663,\n",
       "           153,   153,   153,   153,   153,   153,  6291,  6291,  6291,\n",
       "          6291,   645,  5954,  5954,  5954, 15677, 15677, 15677, 16948,\n",
       "         27526, 30687, 30687, 30687, 21006, 21006, 24316, 24316, 24316,\n",
       "          6680,  6680,  3438,  3621,  3621,  3621,  3621, 28702, 12922],\n",
       "        [21632, 21632, 21632, 21632, 30271, 23491, 23491, 23491, 23491,\n",
       "           247,   247,   247, 12061, 11626, 11626, 10005, 10005,  8678,\n",
       "         14534, 14534, 14534, 14534,  3463,  3463,  3463,  3463, 20030,\n",
       "         20030, 20030, 20030, 20030, 20030, 22995, 22995, 22995, 13857,\n",
       "          2363,  2363,  2363,  2363,  2363,  7874,  7874,  7874, 16141,\n",
       "         16141, 16141, 16141, 13555, 13555,  7918,  7918, 25749, 13263,\n",
       "         13263, 11193, 11193, 11193, 11193, 11193, 11193, 31225, 31225,\n",
       "         31225, 31225, 11393, 11393, 26707, 26707,  8955,  8955,  7208],\n",
       "        [12463, 12463, 12463, 12463, 12463, 12463, 12463, 12463, 12463,\n",
       "         12463, 12463, 12463, 12463,  9934,  9934, 19975,  9934, 19975,\n",
       "         14220, 14220, 14220, 18331, 18331, 28019, 28019, 28997, 28997,\n",
       "          9456,  9456,   908, 14114, 18147, 18147, 18147, 18147, 18179,\n",
       "         25612, 22909, 22909, 22909, 22909, 22909,  6261,  6261,  6261,\n",
       "          6261,  6261, 26173, 26173, 26173, 28021, 28021, 28021, 28021,\n",
       "         28021, 28021, 13325, 13325, 13325,  2006, 14431, 14431, 14431,\n",
       "         14431, 14431, 14431, 11990, 11990, 11990, 11990, 28866, 20084],\n",
       "        [ 4224,  4224, 15016, 15016, 15016, 15016, 16455, 11409, 11409,\n",
       "         11262, 11262, 11262, 10154, 10154, 10154, 10154,  7035,  7035,\n",
       "          7035,  7035,  7035, 20978, 20978, 20978, 20978, 20978, 14780,\n",
       "         14780, 14780, 14780, 25484, 25484, 25484, 25484, 25484, 21047,\n",
       "         21047, 21047, 22903, 22903, 22903, 22903, 24071, 17022, 17022,\n",
       "          5774,  5774, 17022, 27819, 27819, 20714, 20714, 20714, 20714,\n",
       "         20714, 10058, 10058, 10058, 10058, 10058,  9219,  9219,  9219,\n",
       "          9219,  2072,  2072,  2072,  2072,  2072,  2072,  2072, 22870],\n",
       "        [ 6353,  4757,  4757,  4757, 12064, 12064, 12064, 12064, 12064,\n",
       "         12064, 31126, 31126, 31126, 18660, 18660, 18660, 18660, 18660,\n",
       "         22430, 22430, 17518, 19106, 19106, 19106, 19106, 19106,  7162,\n",
       "          7162,  7162,  7162,  7162, 18738, 18738, 10935, 16328, 16328,\n",
       "         16328, 16328, 16328, 15687,  9039,  9039, 16731,  9039,  7042,\n",
       "          7042, 14348, 14348, 14348, 14348,  8801,  8801,  8801, 12610,\n",
       "         12610,  8468,  5511,  5511,  5511,  7917,  7917,  3460, 18155,\n",
       "         18155, 13228, 13228, 24543, 24543,   926,   926,   926,   926],\n",
       "        [20565, 20565, 20565, 20565, 20565, 12656, 12656, 12656, 12656,\n",
       "         18279, 18279, 18279, 18279, 18279, 18279, 16750, 30923, 30923,\n",
       "         30923, 30923, 30923, 30923, 30923, 15158, 15158,  1706,  1706,\n",
       "          1706,  1706,  1706,  1706,  7833,  7833, 24907, 24907, 24907,\n",
       "         24907, 29636,  7235,  7235,  7235, 18554, 20203, 20203, 20203,\n",
       "         20203, 20203, 14094, 14094, 14094, 14094, 12643, 12643, 12643,\n",
       "          2905,  2905,  2905,  2905, 18593, 28550, 16025, 23197, 23197,\n",
       "         23197, 23197,  1991, 18930, 18930, 18930, 18930, 18930, 18930]],\n",
       "       dtype=int32), 10.374412, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:24<00:00,  1.81it/s, accuracy=0.243, cost=4.69]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.80it/s, accuracy=0.285, cost=4.09]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.520177, training avg acc 0.186024\n",
      "epoch 1, testing avg loss 4.517423, testing avg acc 0.256011\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:24<00:00,  1.81it/s, accuracy=0.305, cost=3.8] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.349, cost=3.59]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 4.115769, training avg acc 0.293135\n",
      "epoch 2, testing avg loss 3.909634, testing avg acc 0.317230\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:25<00:00,  1.81it/s, accuracy=0.393, cost=3.15]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.344, cost=3.4] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 3.528581, training avg acc 0.352667\n",
      "epoch 3, testing avg loss 3.618731, testing avg acc 0.350484\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:24<00:00,  1.81it/s, accuracy=0.458, cost=2.64]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.344, cost=3.22]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 3.134520, training avg acc 0.397542\n",
      "epoch 4, testing avg loss 3.489904, testing avg acc 0.367348\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:25<00:00,  1.81it/s, accuracy=0.52, cost=2.26] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.382, cost=3.16]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.835424, training avg acc 0.434863\n",
      "epoch 5, testing avg loss 3.460773, testing avg acc 0.374754\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:24<00:00,  1.81it/s, accuracy=0.569, cost=1.94]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.36, cost=3.2]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 2.593989, training avg acc 0.467825\n",
      "epoch 6, testing avg loss 3.491845, testing avg acc 0.376171\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:24<00:00,  1.81it/s, accuracy=0.6, cost=1.73]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.387, cost=3.17]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 2.392645, training avg acc 0.496659\n",
      "epoch 7, testing avg loss 3.547322, testing avg acc 0.375436\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:23<00:00,  1.81it/s, accuracy=0.647, cost=1.52]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.409, cost=3.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 2.217491, training avg acc 0.522852\n",
      "epoch 8, testing avg loss 3.648002, testing avg acc 0.373227\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:24<00:00,  1.81it/s, accuracy=0.678, cost=1.36]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.88it/s, accuracy=0.419, cost=3.17]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 2.066858, training avg acc 0.546140\n",
      "epoch 9, testing avg loss 3.755751, testing avg acc 0.373071\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:23<00:00,  1.81it/s, accuracy=0.708, cost=1.25]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.87it/s, accuracy=0.414, cost=3.23]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.934539, training avg acc 0.566720\n",
      "epoch 10, testing avg loss 3.881185, testing avg acc 0.369129\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:25<00:00,  1.81it/s, accuracy=0.723, cost=1.17]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.88it/s, accuracy=0.403, cost=3.22]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.817354, training avg acc 0.585581\n",
      "epoch 11, testing avg loss 4.011291, testing avg acc 0.360737\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:24<00:00,  1.81it/s, accuracy=0.736, cost=1.08]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.90it/s, accuracy=0.382, cost=3.43]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.713917, training avg acc 0.602243\n",
      "epoch 12, testing avg loss 4.173558, testing avg acc 0.357972\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:25<00:00,  1.81it/s, accuracy=0.745, cost=0.992]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.88it/s, accuracy=0.366, cost=3.52]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.624407, training avg acc 0.616867\n",
      "epoch 13, testing avg loss 4.297431, testing avg acc 0.352251\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  97%|█████████▋| 1510/1563 [13:53<00:27,  1.92it/s, accuracy=0.692, cost=1.21]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:23<00:00,  1.81it/s, accuracy=0.804, cost=0.762]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.91it/s, accuracy=0.366, cost=3.98]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 1.352435, training avg acc 0.662905\n",
      "epoch 17, testing avg loss 4.806041, testing avg acc 0.347631\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  62%|██████▏   | 967/1563 [08:50<05:07,  1.94it/s, accuracy=0.668, cost=1.35]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [13:51<00:00,  1.88it/s, accuracy=0.839, cost=0.637]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:09<00:00,  4.06it/s, accuracy=0.366, cost=4.24]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.208166, training avg acc 0.689351\n",
      "epoch 20, testing avg loss 5.142049, testing avg acc 0.340047\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:27<00:00,  1.46it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.06368613"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
